const appKey = require('../../config/appKey');
const common = require('../../utils/common');
const redis = require('../../config/redis');
const moment = require('moment');
const axIos = require('axios');
class Sweep {
    /**
     * 扫码洗车
     * @api {POST}        /sweep                 扫码洗车
     * @apiName           /sweep
     * @apiGroup          Sweep
     * @apiParam          {String}         deviceId         设备id
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {}
     }
     */
    async index(ctx) {
        let {
            db,
            model,
            user: { User },
            request: {
                body: { deviceId }
            }
        } = ctx;

        if (!deviceId) {
            ctx.errors('参数错误');
            return;
        }

        let cardInfo = await db.User.findOne({ where: { id: User.id } });

        if (cardInfo.status === false) {
            ctx.errors('账户违规操作，已被封停。');
            return;
        }

        // 查询设备是否在使用
        const { data } = await axIos
            .get('http://xicheba.net/cdyangyang/API/Handler/DeviceOne', {
                params: { apiKey: appKey.appKey, DevCode: deviceId }
            })
            .then(res => res.data);
        console.log(data);
        if (data.UseState !== 0) {
            ctx.errors('设备正在忙碌');
            return;
        }

        // 查询分享限制
        const wash = await db.Setting.findOne();
        // 次卡没用完先用次卡
        const orderNo = await common.randomNo(14);
        // 发送请求启动机器
        let params = {
            apiKey: appKey.appKey,
            DevCode: deviceId,
            OrderNo: orderNo,
            totalFee: appKey.totalFee
        };
        // 查询相关信息
        let merchant = await db.Drives.findOne({
            where: { deviceId: deviceId }
        });

        //判断是否会员，或者有无次卡
        const key = cardInfo.openId;
        let value = await redis.get(key);
        value = JSON.parse(value);
        let info = { count: 1 };
        console.log('今日洗车几次', value);
        if (value) {
            if (value.count >= wash.wash) {
                ctx.errors('今日已到上限');
                return;
            } else {
                value.count++;
                info.count = value.count;
            }
        }
        // 过期时间
        const express =
            Math.round(
                moment()
                    .endOf('day')
                    .valueOf() / 1000
            ) - Math.round(new Date() / 1000);

        let timeCard = await db.TimeCard.findOne({
            where: { id: cardInfo.cardTimeId }
        });

        let memberCard = await db.Members.findOne({
            where: { id: cardInfo.memberId }
        });

        // 发送请求，洗车
        let status;
        // 插入数据、启动事务
        let transaction;
        try {
            transaction = await model.transaction();
            let user = await db.User.findOne({ where: { id: User.id } });

            if (user.reward > 0) {
                // 奖励洗车
                status = await axIos
                    .get(appKey.notify_url, { params })
                    .then(res => res.data);
                if (status.result) {
                    //写入使用表
                    let par = {
                        orderId: orderNo,
                        userId: User.id,
                        merchantId: merchant.merchantId,
                        address: merchant.areaName,
                        deviceId: deviceId,
                        amount: 0.0,
                        payment: '(奖励)次卡支付',
                        type: 1
                    };
                    await db.Use.upsert(par);
                    // 减去洗车次数
                    await db.User.update(
                        { reward: user.reward - 1 },
                        { where: { id: user.id } }
                    );

                    await transaction.commit();

                    console.log('(奖励)次卡支付', status);

                    redis.set(key, JSON.stringify(info));

                    redis.expire(key, express);

                    redis.set(
                        user.openId + deviceId,
                        JSON.stringify({ status: 1, msg: '正在洗车' })
                    );

                    redis.expire(user.openId + deviceId, 1200);
                    ctx.success('启动成功');
                } else {
                    await transaction.rollback();
                    ctx.errors(status.messages);
                    return;
                }
            } else if (user.limit > 0) {
                // 次卡洗车
                status = await axIos
                    .get(appKey.notify_url, { params })
                    .then(res => res.data);
                if (status.result) {
                    //写入使用表
                    let par = {
                        orderId: orderNo,
                        userId: User.id,
                        merchantId: merchant.merchantId,
                        address: merchant.areaName,
                        deviceId: deviceId,
                        amount: 0.0,
                        payment: '次卡支付',
                        type: 2
                    };

                    if (timeCard) {
                        par.amount = timeCard.actualPrice / timeCard.limit;
                    }

                    console.log(par);
                    await db.Use.upsert(par);

                    // 减去洗车次数
                    await db.User.update(
                        { limit: user.limit - 1 },
                        { where: { id: user.id } }
                    );

                    await transaction.commit();

                    console.log('次卡洗车', status);

                    redis.set(key, JSON.stringify(info));

                    redis.expire(key, express);

                    redis.set(
                        user.openId + deviceId,
                        JSON.stringify({ status: 1, msg: '正在洗车' })
                    );

                    redis.expire(user.openId + deviceId, 1200);
                    ctx.success('启动成功');
                } else {
                    await transaction.rollback();
                    ctx.errors(status.messages);
                    return;
                }
            } else if (user.leftDay > 0) {
                // 会员卡洗车
                status = await axIos
                    .get(appKey.notify_url, { params })
                    .then(res => res.data);
                if (status.result) {
                    //写入使用表
                    let row = {
                        orderId: orderNo,
                        userId: User.id,
                        merchantId: merchant.merchantId,
                        deviceId: deviceId,
                        address: merchant.areaName,
                        amount: memberCard.actualPrice / memberCard.limit,
                        payment: '会员卡支付',
                        type: 3
                    };
                    await db.Use.upsert(row);
                    await transaction.commit();

                    console.log('会员卡洗车', status);

                    redis.set(key, JSON.stringify(info));
                    redis.expire(key, express);
                    redis.set(
                        user.openId + deviceId,
                        JSON.stringify({ status: 1, msg: '正在洗车' })
                    );
                    redis.expire(user.openId + deviceId, 1200);
                    ctx.success('启动成功');
                } else {
                    await transaction.rollback();
                    ctx.errors(status.messages);
                    return;
                }
            } else {
                ctx.errors('您不是会员');
                return;
            }
        } catch (e) {
            // rollback transaction
            console.log(e);
            await transaction.rollback();
            ctx.errors('启动失败');
            return;
        }
    }
}
module.exports = new Sweep();
